#include "bga/graphics/PositionInterpolator.h"

#include "bga/math/Vector3.h"

#include <iostream>

#define EPSILON 1e-3

using namespace std;

namespace bga
{

PositionInterpolator::PositionInterpolator(float animationTime, SceneNode* node):
                                                animationTime(animationTime),
                                                node(node),
                                                currentT(0.f)
{
    /// We are going to do interpolate the quaternion 60 times per second
    this->timer.setTime(100.f/6.f);
    this->timer.addTimerListener(*this);
}

PositionInterpolator::~PositionInterpolator()
{

}

void PositionInterpolator::setNode(SceneNode* node)
{
    this->node = node;
}

void PositionInterpolator::startAnimation(const Point3f& initial, const Point3f& final)
{
    if(!this->timer.isStarted() && this->node != NULL)
    {
        this->initial = initial;
        this->final = final;

        currentT = 100.f/(6.f * this->animationTime);
        unaryVector.setX((this->final.getX() - this->initial.getX()) * currentT) ;
        unaryVector.setY((this->final.getY() - this->initial.getY()) * currentT);
        unaryVector.setZ((this->final.getZ() - this->initial.getZ()) * currentT);

        this->timer.start();
    }
}

bool PositionInterpolator::isRunning() const
{
    return this->timer.isStarted();
}

void PositionInterpolator::timeElapsed(const bga::TimerEvent &event)
{
    this->node->translate(unaryVector.getX(), unaryVector.getY(), unaryVector.getZ());
    if(currentT >= 1 - EPSILON)
    {
        this->timer.stop();
    }
    currentT += 100.f/(6.f * this->animationTime);
}

}
